package com.sgb.kjwl.viewmodel.transport;

import android.app.Application;
import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.sgb.kjwl.api.APIManager;
import com.swgk.core.base.api.ICallBack;
import com.sgb.kjwl.api.MeManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.CarInfo;
import com.sgb.kjwl.model.entity.DriverInfo;
import com.sgb.kjwl.model.entity.GoodsOrderEntity;
import com.sgb.kjwl.model.entity.self.GoodsSourceDetail;
import com.sgb.kjwl.model.entity.self.UserAccount;
import com.sgb.kjwl.model.entity.shopping.PayCardEntity;
import com.sgb.kjwl.model.entity.transport.GoodsSourcePlace;
import com.sgb.kjwl.model.entity.transport.PayInfoEntity;
import com.sgb.kjwl.model.entity.transport.SingleItemConstant;
import com.sgb.kjwl.model.entity.transport.SingleItemEntity;
import com.sgb.kjwl.utils.EntityConversion;
import com.sgb.kjwl.utils.NumberUtil;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.view.ui.activity.transport.PayGoodsOrderActivity;
import com.sgb.link.entity.AMapAddressEntity;
import com.sgb.link.utils.AddressHelper;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.StringUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author: 王彬臣
 * @date: 2021/2/7
 * @Description: 接单viewModel
 */
public class PayGoodsViewModel extends AndroidViewModel {

    public MutableLiveData<List<CarInfo>> ldCar = new MutableLiveData<>();
    public MutableLiveData<List<CarInfo>> ldCarinfo = new MutableLiveData<>();
    public MutableLiveData<AMapAddressEntity> ldLocation = new MutableLiveData<>();
    public MutableLiveData<DriverInfo> ldDriverInfo = new MutableLiveData<>();
    public MutableLiveData<PayInfoEntity> ldTradeNo = new MutableLiveData<>();
    public MutableLiveData<PayInfoEntity> ldUnfreeze = new MutableLiveData<>();
    public MutableLiveData<GoodsSourceDetail> soureDetail = new MutableLiveData<>();
    GoodsSourceDetail goodsSourcePkace;
    String bankInfo = "";

    public PayGoodsViewModel(@NonNull Application application) {
        super(application);
    }


    /**
     * 获取车辆信息
     */
    public void getCarInfo(Context context) {
        DialogHelper.showProgressDialog(context, "请求中...");
        APIManager.getInstance().getDriverAPI().getCarInfo().enqueue(new ICallBack<BaseEntity<List<CarInfo>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CarInfo>> data) {
                ldCar.postValue(data.getData());
            }
        });
    }

    /**
     * 获取车辆信息
     */
    public void getReFreshCarInfo(Context context) {
        DialogHelper.showProgressDialog(context, "请求中...");
        APIManager.getInstance().getDriverAPI().getCarInfo().enqueue(new ICallBack<BaseEntity<List<CarInfo>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CarInfo>> data) {
                ldCarinfo.postValue(data.getData());
            }
        });
    }

    /**
     * 获取定位信息
     */
    public void getCurrentLocation(Context context) {
        AddressHelper.getInstance().getCurrentLocation(context, entity -> {
            if (entity != null) {
                ldLocation.postValue(entity);
            }
        });
    }

    /**
     * 设置货源信息
     */
    public void syncGoodsInfo(List<SingleItemEntity> list, GoodsSourceDetail goodsSourcePkace) {
        this.goodsSourcePkace = goodsSourcePkace;
        list.clear();
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "包装方式", TextUtils.isEmpty(goodsSourcePkace.getPackingModeName()) ? "无" : goodsSourcePkace.getPackingModeName()));
        GoodsSourcePlace mgoodsSourcePkace;
        if (goodsSourcePkace.getPlace() == null) {
            mgoodsSourcePkace = EntityConversion.modelA2B(goodsSourcePkace, GoodsSourcePlace.class);
        } else {
            mgoodsSourcePkace = goodsSourcePkace.getPlace();
        }
        if ("11".equals(goodsSourcePkace.getHandleTypeNo())) {//一装一卸
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "装货地", mgoodsSourcePkace.getProvinceName() + mgoodsSourcePkace.getCityName() + mgoodsSourcePkace.getDistrictName() + mgoodsSourcePkace.getDetailAddress()));
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "卸货地", mgoodsSourcePkace.getDestProvinceName() + mgoodsSourcePkace.getDestCityName() + mgoodsSourcePkace.getDestDistrictName() + mgoodsSourcePkace.getDestDetailAddress()));
        } else if ("12".equals(goodsSourcePkace.getHandleTypeNo())) {//一装两卸
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "装货地", mgoodsSourcePkace.getProvinceName() + mgoodsSourcePkace.getCityName() + mgoodsSourcePkace.getDistrictName() + mgoodsSourcePkace.getDetailAddress()));
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "卸货地1", mgoodsSourcePkace.getViaDestProvinceName() + mgoodsSourcePkace.getViaDestCityName() + mgoodsSourcePkace.getViaDestDistrictName() + mgoodsSourcePkace.getViaDestDetailAddress()));
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "卸货地2", mgoodsSourcePkace.getDestProvinceName() + mgoodsSourcePkace.getDestCityName() + mgoodsSourcePkace.getDestDistrictName() + mgoodsSourcePkace.getDestDetailAddress()));
        } else if ("21".equals(goodsSourcePkace.getHandleTypeNo())) {//两装一卸
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "装货地1", mgoodsSourcePkace.getProvinceName() + mgoodsSourcePkace.getCityName() + mgoodsSourcePkace.getDistrictName() + mgoodsSourcePkace.getDetailAddress()));
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "装货地2", mgoodsSourcePkace.getViaSendProvinceName() + mgoodsSourcePkace.getViaSendCityName() + mgoodsSourcePkace.getViaSendDistrictName() + mgoodsSourcePkace.getViaSendDetailAddress()));
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "卸货地", mgoodsSourcePkace.getDestProvinceName() + mgoodsSourcePkace.getDestCityName() + mgoodsSourcePkace.getDestDistrictName() + mgoodsSourcePkace.getDestDetailAddress()));
        } else if ("22".equals(goodsSourcePkace.getHandleTypeNo())) {
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "装货地1", mgoodsSourcePkace.getProvinceName() + mgoodsSourcePkace.getCityName() + mgoodsSourcePkace.getDistrictName() + mgoodsSourcePkace.getDetailAddress()));
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "装货地2", mgoodsSourcePkace.getViaSendProvinceName() + mgoodsSourcePkace.getViaSendCityName() + mgoodsSourcePkace.getViaSendDistrictName() + mgoodsSourcePkace.getViaSendDetailAddress()));
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "卸货地1", mgoodsSourcePkace.getViaDestProvinceName() + mgoodsSourcePkace.getViaDestCityName() + mgoodsSourcePkace.getViaDestDistrictName() + mgoodsSourcePkace.getViaDestDetailAddress()));
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "卸货地2", mgoodsSourcePkace.getDestProvinceName() + mgoodsSourcePkace.getDestCityName() + mgoodsSourcePkace.getDestDistrictName() + mgoodsSourcePkace.getDestDetailAddress()));
        }

        list.add(new SingleItemEntity(SingleItemConstant.TYPE_FOUR));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "装车要求", TextUtils.isEmpty(goodsSourcePkace.getLoadRequire()) ? "/" : goodsSourcePkace.getloadRequireWords()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "卸车要求", TextUtils.isEmpty(goodsSourcePkace.getUnloadRequire()) ? "/" : goodsSourcePkace.getUnloadRequireWords()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "装车时间", goodsSourcePkace.getShipmentTime()==null?"/":DateUtils.stampToDay5(goodsSourcePkace.getShipmentTime() + "") + "-" + (goodsSourcePkace.getShipmentEndTime()==null?"/":DateUtils.stampToDay5(goodsSourcePkace.getShipmentEndTime() + ""))));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "到货时间", goodsSourcePkace.getArrivalTime()==null?"/":"自装货结束日期" + goodsSourcePkace.getArrivalTime() + "天内"));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "付款方式", TextUtils.isEmpty(goodsSourcePkace.getPayType()) ? "/" : goodsSourcePkace.getPayType()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "收款账户要求", TextUtils.isEmpty(goodsSourcePkace.getOtherPaymentRequire()) ? "/" : goodsSourcePkace.getOtherPaymentRequire()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "发票要求", TextUtils.isEmpty(goodsSourcePkace.getInvoice()) ? "/" : goodsSourcePkace.getInvoiceWords()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "税率", TextUtils.isEmpty(goodsSourcePkace.getTariff()) ? "/" : NumberUtil.trim0(goodsSourcePkace.getTariff()) + "%"));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "货物损坏/丢失赔偿约定", TextUtils.isEmpty(goodsSourcePkace.getLostPromise()) ? "/" : goodsSourcePkace.getLostPromise()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_TWO, "履约保证金", TextUtils.isEmpty(goodsSourcePkace.getPerformanceBond()) ? "/" : NumberUtil.trim0(goodsSourcePkace.getPerformanceBond()) + "元", Color.parseColor("#FF6600")));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_TWO, "信息费", NumberUtil.trim0(goodsSourcePkace.getMessagePrice()) + "元", Color.parseColor("#FF6600")));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "逾期装货或到货违约责任约定", TextUtils.isEmpty(goodsSourcePkace.getOverduePromise()) ? "/" : goodsSourcePkace.getOverduePromise()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "其他约定", TextUtils.isEmpty(goodsSourcePkace.getOverduePromise()) ? "/" : goodsSourcePkace.getOverduePromise()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_FOUR));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "发货单位", TextUtils.isEmpty(goodsSourcePkace.getSendGoodsUnit()) ? "/" : goodsSourcePkace.getSendGoodsUnit()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "联系人", TextUtils.isEmpty(goodsSourcePkace.getSendPeople()) ? "/" : StringUtil.goneName(goodsSourcePkace.getSendPeople())));
        if (TextUtils.isEmpty(goodsSourcePkace.getReceptionPhone())) {
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "联系电话", "/"));
        } else {
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_THREE, "联系电话", TextUtils.isEmpty(goodsSourcePkace.getSendPhone()) ? "" : goodsSourcePkace.getSendPhone()));
        }
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_FOUR));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "收货单位", TextUtils.isEmpty(goodsSourcePkace.getReceiveGoodsUnit()) ? "/" : goodsSourcePkace.getReceiveGoodsUnit()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "联系人", TextUtils.isEmpty(goodsSourcePkace.getReceptionPeople()) ? "/" : StringUtil.goneName(goodsSourcePkace.getReceptionPeople())));
        if (TextUtils.isEmpty(goodsSourcePkace.getReceptionPhone())) {
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "联系电话", "/"));
        } else {
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_THREE, "联系电话", goodsSourcePkace.getReceptionPhone()));
        }

    }

    /**
     * 设置车辆信息
     */
    public void syncCarInfo(List<SingleItemEntity> list, DriverInfo info) {
        list.clear();
        if(goodsSourcePkace!=null) {
            list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "可装车时间", goodsSourcePkace.getShipmentTime() == null ? "/" : DateUtils.stampToDay5(goodsSourcePkace.getShipmentTime() + "") + "-" + (goodsSourcePkace.getShipmentEndTime() == null ? "/" : DateUtils.stampToDay5(goodsSourcePkace.getShipmentEndTime() + ""))));
        }
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "司机姓名", TextUtils.isEmpty(info.getName()) ? "/" : info.getName()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "联系电话", TextUtils.isEmpty(info.getTelphone()) ? "/" : info.getTelphone()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "年龄", TextUtils.isEmpty(info.getCarAge()) ? "/" : info.getCarAge()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "驾龄", TextUtils.isEmpty(info.getDriverAge()) ? "/" : info.getDriverAge()));
        list.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, "收款账户", TextUtils.isEmpty(bankInfo) ? "/" : bankInfo));
    }

    /**
     * 获取货源详情
     */
    public void getGoodsDetail(Context activity, String sourceNo, List<SingleItemEntity> mGoodsList) {
        DialogHelper.showProgressDialog(activity, null, "加载中", 0, true, null).setCanceledOnTouchOutside(false);
        String isLogin = UserOperating.getInstance().isLogged() ? "true" : "false";
        NewAPIManager.getInstance().getLogisticsAPI().getGoodsSourceDetail(isLogin, sourceNo,null).enqueue(new Callback<BaseEntity<GoodsSourceDetail>>() {
            @Override
            public void onResponse(Call<BaseEntity<GoodsSourceDetail>> call, Response<BaseEntity<GoodsSourceDetail>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getState().equals("ok")) {
                    syncGoodsInfo(mGoodsList, response.body().getData());
                    soureDetail.postValue(response.body().getData());
                } else if (response.body().getState().equals("fail")) {
                    MToast.showToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<GoodsSourceDetail>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, "操作失败");
            }
        });
    }

    /**
     * 接单
     */
    public void quotation(Context context, GoodsOrderEntity entity) {
        DialogHelper.showProgressDialog(context, null, "加载中", 0, true, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getLogisticsAPI().orderTaking(entity).enqueue(new Callback<BaseEntity<PayInfoEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<PayInfoEntity>> call, Response<BaseEntity<PayInfoEntity>> response) {
                if (response.body() == null || response.body().getState() == null) return;
                DialogHelper.dismissProgressDialog();
                if (response.body().getState().equals("ok")) {
                    PayInfoEntity payInfoEntity = response.body().getData();
                    if (payInfoEntity==null||payInfoEntity.getResult()==null){
                        return;
                    }
                    switch (payInfoEntity.getResult()) {
                        case "200":
                            ldTradeNo.postValue(response.body().getData());
                            break;
                        default:
                            MToast.showToast(context, payInfoEntity.getMessage());
                            break;
                    }


                } else {

                    MToast.showToast(context, TextUtils.isEmpty(response.body().getMsg()) ? "fail" : response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<PayInfoEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }
    /**
     * 接单
     */
    public void getoperateInquiryOrderTaking(Context context, GoodsOrderEntity entity) {
        DialogHelper.showProgressDialog(context, null, "加载中", 0, true, null).setCanceledOnTouchOutside(false);
        Map<String, Object> map = new HashMap<>();
        //todo 换接口
        NewAPIManager.getInstance().getLogisticsAPI().getoperateInquiryOrderTaking(entity).enqueue(new Callback<BaseEntity<PayInfoEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<PayInfoEntity>> call, Response<BaseEntity<PayInfoEntity>> response) {
                //  APIManager.getInstance().changeAPIManager(UrlConfig.BASE_URL);
                if (response.body() == null || response.body().getState() == null) return;
                DialogHelper.dismissProgressDialog();
                if (response.body().getState().equals("ok")) {
                    PayInfoEntity payInfoEntity = response.body().getData();
                    if (payInfoEntity==null||payInfoEntity.getResult()==null){
                        return;
                    }
                    switch (payInfoEntity.getResult()) {
                        case "200":
                            ldTradeNo.postValue(response.body().getData());
                            break;
                        default:
                            MToast.showToast(context, payInfoEntity.getMessage());
                            break;
                    }


                } else {

                    MToast.showToast(context, TextUtils.isEmpty(response.body().getMsg()) ? "fail" : response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<PayInfoEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                // APIManager.getInstance().changeAPIManager(UrlConfig.BASE_URL);
            }
        });
    }

    public void getDriverInfo() {
        NewAPIManager.getInstance().getLogisticsAPI().getDriverInfo().enqueue(new Callback<BaseEntity<DriverInfo>>() {
            @Override
            public void onResponse(Call<BaseEntity<DriverInfo>> call, Response<BaseEntity<DriverInfo>> response) {
                if (response.body() == null || response.body().getState() == null) return;

                if (response.body().getState().equals("ok")) {
                    ldDriverInfo.setValue(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<DriverInfo>> call, Throwable t) {
            }
        });
    }

    public void isFirstPay(PayGoodsOrderActivity activity) {
        DialogHelper.showProgressDialog(activity, null, "加载中", 0, true, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getDriverAPI().isFirstPay().enqueue(new Callback<BaseEntity<UserAccount>>() {
            @Override
            public void onResponse(Call<BaseEntity<UserAccount>> call, Response<BaseEntity<UserAccount>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) return;
                if (response.body().getState().equals("ok")) {
                    if (response.body().getData().isFirstPay()) {
                        activity.showTextDialog(true);
                    } else {
                        activity.toPayOrder();
                    }
                } else {
                    MToast.showToast(activity, TextUtils.isEmpty(response.body().getMsg()) ? "fail" : response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<UserAccount>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });

    }

    public void getQuickBankList(PayGoodsOrderActivity activity) {

        MeManager.getInstance().getMaterialAPI().getQuick().enqueue(new Callback<BaseEntity<List<PayCardEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PayCardEntity>>> call, Response<BaseEntity<List<PayCardEntity>>> response) {


                if (response.body() == null) return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if (response.body().getData() != null && response.body().getData().size() > 0) {
                        bankInfo = response.body().getData().get(0).openingBank;
                    } else {
                        bankInfo = "";
                    }

                } else {
                    MToast.showToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PayCardEntity>>> call, Throwable t) {
                MToast.showToast(activity, t.getMessage());
            }
        });
    }
    /**
     * 取消支付立即解冻当前货源
     * @param goodsSourceNo
     * @param orderNo
     */
    public void unfreeze(Context activity,String goodsSourceNo, String orderNo) {
        //showLoadingView();
        Map<String, Object> map = new HashMap<>();
        map.put("orderNo", orderNo);
        map.put("goodsSourceNo", goodsSourceNo);
        NewAPIManager.getInstance().getLogisticsAPI().unfreeze(map).enqueue(new Callback<BaseEntity<PayInfoEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<PayInfoEntity>> call, Response<BaseEntity<PayInfoEntity>> response) {
                // showContentView();
                if (response.body()==null)return;
                if (response.body().getState().equals("ok")) {
                    ldUnfreeze.postValue(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<PayInfoEntity>> call, Throwable t) {
                MToast.showToast(activity, t.getMessage());
            }
        });
    }
}
